<template>
  <div>
    <!--搜索框-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="部门" prop="selectDept">
        <el-cascader v-model="selectDept" :options="deptList" :props="{ checkStrictly: true }" @change="handleSelectDept" size="small" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="销售" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择销售人员" filterable @change="handleSelectUser" size="small" clearable>
          <el-option
            v-for="item in deptUserList"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户ID" prop="crmId">
        <el-input
          v-model="queryParams.crmId"
          placeholder="请输入crm客户id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户号码" prop="cdrCustomerNumber">
        <el-input
          v-model="queryParams.cdrCustomerNumber"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="回呼号码" prop="cdrHotline">
        <el-input
          v-model="queryParams.cdrHotline"
          placeholder="请输入回呼号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工号" prop="cdrCalleeCno">
        <el-input
          v-model="queryParams.cdrCalleeCno"
          placeholder="请输入工号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通话标识" prop="cdrMainUniqueId">
        <el-input
          v-model="queryParams.cdrMainUniqueId"
          placeholder="请输入通话标识"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="呼叫状态" prop="cdrStatus">
        <el-select v-model="queryParams.cdrStatus" placeholder="请选择呼叫状态" size="small" clearable>
          <el-option label="接通" :value="1"></el-option>
          <el-option label="未接通" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          size="small"
          style="width: 215px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">搜索</el-button>
        <el-button size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-card class="box-card" shadow="hover">
    <!--数据表格-->
      <el-table
        border
      :data="recordList"
      v-loading="loading"
      stripe
      style="width: 100%"
    >
      <el-table-column prop="cdrCalleeCno" label="座席工号"></el-table-column>
      <el-table-column label="部门" align="center" prop="deptName"/>
      <el-table-column label="销售" prop="nickName"></el-table-column>
      <el-table-column label="客户ID" prop="crmId" width="100"></el-table-column>
      <el-table-column label="回呼号码" prop="cdrHotline" width="120"></el-table-column>
      <el-table-column label="客户号码" prop="mobileHidden" width="120">
        <!--        <template slot-scope="scope">{{scope.row.cdrCustomerNumber|telAnonymity}}</template>-->
      </el-table-column>
      <!--      <el-table-column label="类型" :formatter="telTypeFormat"> </el-table-column>-->
      <el-table-column label="呼叫状态" :formatter="cdrStatusFormat" width="160"></el-table-column>
      <el-table-column prop="cdrStartTime" label="呼入/座席接听时间" width="160">
        <template slot-scope="scope">
          {{ scope.row.cdrStartTime * 1000|dataFormat }}<br/>
          {{ scope.row.cdrBridgeTime * 1000|dataFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="cdrStartTime" label="挂机时间" width="160">
        <template slot-scope="scope">
          {{ scope.row.cdrEndTime * 1000|dataFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="cdrEndTimeCdrBridgeTime" :formatter="callDurationFormat" label="通话时长" width="90"
      ></el-table-column>
      <el-table-column prop="comment" label="备注" show-overflow-tooltip></el-table-column>
      <el-table-column label="录音文件" width="380">
        <template slot-scope="scope">
          <audio
          v-if="scope.row.cosRecordUrl"
          :key="'audio_'+scope.row.cdrId"
          preload="none"
          :controlsList="hasPerm(['crm:outcallRecord:download'])?'':'nodownload'"
          controls
          class="callRecord-radio"
          >
          <source :src="scope.row.cosRecordUrl" type="audio/mpeg">
          您的浏览器不支持该音频格式。
        </audio>
        <span v-else>暂无</span>
      </template>
    </el-table-column>
    <el-table-column label="呼叫类型" :formatter="cdrCallTypeFormat" width="120"></el-table-column>
    <el-table-column prop="cdrCustomerAreaCode" label="区号"></el-table-column>
    <el-table-column label="所属省市" width="150">
      <template slot-scope="scope">
        {{ scope.row.cdrCustomerProvince|formatVal }}/{{ scope.row.cdrCustomerCity|formatVal }}
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="176">
      <template slot-scope="scope">
          <el-button size="mini" type="text" @click="openCallDetailsDialog(scope.row.cdrId)" icon="el-icon-document">
            详细
          </el-button>
          <el-button size="mini" type="text" @click="handleCusDetailNew(scope.row)" icon="el-icon-document">
            客户详情
          </el-button>
          <el-button v-if="scope.row.comment" size="mini" type="text" @click="handleComment(scope.row, 'update')" icon="el-icon-edit-outline" >修改备注</el-button>
          <el-button v-else size="mini" type="text" @click="handleComment(scope.row, 'add')" icon="el-icon-edit-outline" >备注 </el-button>
          <template v-if="scope.row.cosRecordUrl" >
            <el-tooltip class="item" effect="dark" content="右键链接另存为" placement="top-start">
              <a class="el-button el-button--text el-button--mini" :href="scope.row.cosRecordUrl" :download="scope.row.cdrId+'.mp3'" v-hasPermi="['crm:outcallRecord:download']" target="_blank"><i class="el-icon-download"></i> 下载录音</a>
            </el-tooltip>
          </template>
        </template>
      </el-table-column>
    </el-table>
      <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!--通话详情-->
    <el-dialog
      title="回呼详情"
      :visible.sync="dialogVisible"
      width="60%"
      :open="handleOpen"
    >
      <!--通话详情组件-->
      <call-record-details :cdr-id="recordId" :call-type="1"></call-record-details>
      <span slot="footer" class="dialog-footer">
<!--        <el-button @click="dialogVisible = false">取 消</el-button>-->
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加通话记录信息对话框 -->
    <el-dialog title="通话备注" :visible.sync="callOpen" width="560px">
      <el-form ref="callForm" :model="callForm" :rules="rulesCall" label-width="110px" class="modal_form">
        <input type="hidden" v-if="callForm.distId" label="资源ID" name="distId" v-model="callForm.distId"/>
        <input type="hidden" label="通话唯一Id" name="callId" v-model="callForm.callId"/>
        <input type="hidden" label="客户Id" name="crmId" v-model="callForm.crmId"/>
        <el-form-item label="呼叫类型" prop="callType" v-show="!callFormEdit" class="modal_form_item">
          <el-select v-model="callForm.callType" placeholder="请选择呼叫类型" style="width: 100%">
            <el-option
              v-for="dict in dict.type.crm_call_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注类型" prop="commentType" class="modal_form_item">
          <el-select v-model="callForm.commentType" placeholder="请选择备注类型" style="width: 100%">
            <el-option
              v-for="dict in dict.type.crm_call_com_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="comment" class="modal_form_item">
          <el-input maxlength="500" type="textarea" show-word-limit v-model="callForm.comment" placeholder="请输入本次通话备注.."/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCalled()" v-show="callFormEdit">修改</el-button>
        <el-button type="primary" @click="submitCalled(1)" v-show="!callFormEdit">保存客户</el-button>
        <el-button type="primary" @click="submitCalled(2)" v-show="!callFormEdit">保存并归档</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, treeselect } from '@/api/system/dept';
import { getCallBackList } from '@/api/call/call';
import {getUserList} from "@/api/system/user";
import { mapState, mapGetters } from 'vuex';
import { formatDate } from '@/utils/index';
import CallRecordDetails from './CallRecordDetails';
import { callNote } from './mixin/record';

//封装的下载流文件的方法
function downloadBlobFile(_method,_url){
  const request = new XMLHttpRequest()	//
  request.open(_method,_url)	//这里替换
  request.send()
  request.responseType = 'blob'	//请求流文件
  return request
}
export default {
  name: 'CallRecord',
  props: [
    'crmId'  // 如果有crmId则查询指定crmId下的记录，默认查询当前用户下的所有通话记录
  ],
  components: {
    CallRecordDetails
  },
  mixins: [callNote],
  data() {
    return {
      // 详情ID
      recordId: 0,
      // 详情弹窗
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通话记录表格数据
      recordList: [],
      // 企业字典
      deptList: [],
      deptOptions: [],
      selectDept: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        crmId: null,
        //nickName: null,
        cdrCalleeCno: null,
        userId: null,
        cdrCustomerNumber: null,
        cdrMainUniqueId: null,
        cdrStatus: null,
        cdrHotline:null
      },
      daterangeCreateTime: [(new Date(new Date().getTime() - 24 * 60 * 60 * 30000)).getFullYear() + '-' + ((new Date(new Date().getTime() - 24 * 60 * 60 * 30000 )).getMonth() + 1) + '-' + ((new Date(new Date().getTime() - 24 * 60 * 60 * 30000)).getDate()), (new Date).getFullYear() + '-' + ((new Date).getMonth() + 1) + '-' + ((new Date).getDate() + 1)],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            end.setTime(end.getTime() + 3600 * 1000 * 24);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            end.setTime(end.getTime() + 3600 * 1000 * 24);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            end.setTime(end.getTime() + 3600 * 1000 * 24);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 选中用户的ID
      deptUserId: '',
      // 部门所有销售
      deptUserList: []
    };
  },
  dicts: ['crm_call_status', 'crm_call_type', 'crm_call_com_type'],
  computed: {
    ...mapState({
      agentId: state => state.user.agentId
    }),
    ...mapGetters('call', ['getCdrStatusText', 'getCallTypeText', 'getTelTypeText'])
  },
  filters: {
    formatVal(value) {
      return value ? value : '-';
    },
    dataFormat(value) {
      return formatDate(value) || '-';
    }
  },
  mounted() {
    // this.agentId && this.getList()
    this.getList();
    this.getListDepts();
  },
  activated() {
    this.getList();
  },
  methods: {
    //判断权限
    hasPerm(binding) {
      const value = binding
      const all_permission = "*:*:*";
      const permissions = this.$store.getters && this.$store.getters.permissions

      if (value && value instanceof Array && value.length > 0) {
        const permissionFlag = value

        const hasPermissions = permissions.some(permission => {
          return all_permission === permission || permissionFlag.includes(permission)
        })
        return hasPermissions
      } else {
        return false
      }
    },
    /** 查询部门用户列表 */
    getDeptUserList() {
      getUserList({
        deptId: this.queryParams.deptId
      }).then(response => {
        this.deptUserList = response.rows;
      });
    },
    /** 选中部门的Id*/
    handleSelectDept(deptId) {
      if (deptId.length == 0) {
        return;
      }
      if (deptId.length > 0) {
        deptId = this.selectDept[this.selectDept.length - 1];
      }
      console.log(deptId);
      this.deptUserId = '';
      this.queryParams.userId=null;
      this.queryParams.deptId = parseInt(deptId);
      this.getDeptUserList();
    },
    /** 选中用户的Id*/
    handleSelectUser(userId) {
      this.deptUserId = userId;
    },
    // 打开详情弹窗
    openCallDetailsDialog(cdrId) {
      this.dialogVisible = true;
      this.recordId = cdrId || 0;
    },
    // 详情弹窗
    handleOpen() {

    },
    // 呼叫状态
    cdrStatusFormat(row, column) {
      return this.selectDictLabel(this.dict.type.crm_call_status, row.cdrStatus) || '-';
    },
    // 呼叫类型
    cdrCallTypeFormat(row, column) {
      return this.selectDictLabel(this.dict.type.crm_call_type, row.cdrCallType) || row.cdrCallType || '-';
    },
    // 电话类型
    telTypeFormat(row, column) {
      return row.cdrCustomerNumberType ? this.getTelTypeText(row.cdrCustomerNumberType) : '-';
    },
    // 通话时长
    callDurationFormat(row, column) {
      let timeArr = (row.cdrEndTimeCdrBridgeTime || '').split('-') || [];
      if (timeArr && timeArr[0] && timeArr[1]) {
        let dr = timeArr[0] - timeArr[1];
        return this.timeToHMS(dr);
      }
      return 0;
    },
    timeToHMS(data) {
      let h = Math.floor(data / 3600) < 10 ? '0' + Math.floor(data / 3600) : Math.floor(data / 3600);
      let m = Math.floor((data / 60 % 60)) < 10 ? '0' + Math.floor((data / 60 % 60)) : Math.floor((data / 60 % 60));
      let s = Math.floor((data % 60)) < 10 ? '0' + Math.floor((data % 60)) : Math.floor((data % 60));
      return h + ':' + m + ':' + s;
    },
    /** 查询CRM客户信息列表 */
    getList() {
      let { agentId, crmId } = this;
      this.loading = true;
      this.queryParams.params = {};
      // this.queryParams.cdrCno = agentId;
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params['startTime'] = this.daterangeCreateTime[0];
        this.queryParams.params['cdrEndTime'] = this.daterangeCreateTime[1];
      }
      // if (this.deptUserId) {
      //   this.queryParams.userId = parseInt(this.deptUserId);
      // }
      if (crmId) {
        this.queryParams.crmId = crmId;
      }
      getCallBackList(this.queryParams).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime =  [(new Date(new Date().getTime() - 24 * 60 * 60 * 30000)).getFullYear() + '-' + ((new Date(new Date().getTime() - 24 * 60 * 60 * 30000 )).getMonth() + 1) + '-' + ((new Date(new Date().getTime() - 24 * 60 * 60 * 30000)).getDate()), (new Date).getFullYear() + '-' + ((new Date).getMonth() + 1) + '-' + ((new Date).getDate() + 1)];
      this.selectDept = [];
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 查询所负责部门
    getListDepts() {
      let deptParams = JSON.parse('{"status":"0", "del_flag": "0"}');
      treeselect(deptParams).then(response => {
        this.deptList = response.data;
      });
      listDept(deptParams).then(response => {
        this.deptOptions = response.data;
      });
    },
    // 部门字典翻译
    deptIdFormat(row, column) {
      for (const item of this.deptOptions) {
        if (item.deptId == row.deptId) {
          return item.deptName;
        }
      }
      return row.deptId || '-';
    },

    //跳转 新客户详情
    handleCusDetailNew(row) {
      this.$router.push({
        path: '/crm/customerDetail/index',
        query: { crmId: btoa(row.crmId) }
      })
    },

  }
};
</script>
<style lang="scss" scoped>
.callRecord-radio {
  width: 300px;
  height: 35px;
}
.app-container{
  //background: #f5f7f9;
  ::v-deep .el-card__header{
    padding: 0;
    line-height: 60px;
  }
  .header_btn{
    display: inline-block;
    //float: right;
  }
}
.modal_form {
  .modal_form_item{
    width: 420px;
    display: inline-block
  }
  .modal_form_items{
    width: 470px;
  }
  ::v-deep .el-input__inner {
    font-size: 13px;
  }
  ::v-deep .el-textarea__inner {
    height: 120px;
  }
}
@media screen and (max-width:1480px) {
  ::v-deep .el-dialog{
    left: 130px;
  }
}
</style>
